package swingExtended.swingWorkers;

import java.lang.reflect.InvocationTargetException;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

/**
 *
 * @author g1wshimu
 */
public abstract class SwingWorkerX<T1, T2> extends SwingWorker<T1, T2>{
    
    /**
     * Called first, synchronously in doInBackground. 
     */
    protected void start() throws Exception {    
    }

    protected abstract T1 doInBackgroundHelper() throws Exception;
        
    private  Exception startException = null;
    
    @Override
    protected final T1 doInBackground() throws Exception { 
        
        try {
            SwingUtilities.invokeAndWait(new Runnable(){
                @Override
                public void run() {
                    try {
                        start();
                    } catch(Exception ex) {
                        startException = ex;
                    }
                    
                }
            });
        } catch (InterruptedException ex) {
            System.err.println("Interrupted while trying to start!");
        } catch (InvocationTargetException ex) {
            throw new Exception(ex.getCause());
        }
        if (startException != null) {
            Exception temp = startException;
            startException = null;
            throw temp;            
        }
        return doInBackgroundHelper();
    }
}
